﻿using System.Collections.Generic;
using System.Linq;
using UcAsp.Net.Model;

namespace UcAsp.Net.MSSQLDAL
{
    public class CourseDAL : UcAsp.Net.IDAL.ICourseDAL
    {
        public List<Course> Select(int pagesize, int pageindex, out int pagecount)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                List<Course> list = new List<Course>();
                var query = entities.Courses;
                pagecount = (query.Count() / pagesize) + 1;
                list = query.OrderBy(o => o.ID).Skip(pagesize * pageindex).Take(pagesize).ToList();
                return list;
            }
        }

        public Course GetCourseByID(int id)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                Course course = entities.Courses.FirstOrDefault(o => o.ID == id);
                return course;
            }
        }

        public List<Course> GetCourseByActionID(int pagesize, int pageindex, out int pagecount, int actionid)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                List<Course> list = new List<Course>();
                var query = entities.Courses.Where(o => o.ActionId == actionid);
                pagecount = (query.Count() / pagesize) + 1;
                list = query.OrderBy(o => o.ID).Skip(pagesize * pageindex).Take(pagesize).ToList();
                return list;
            }
        }

        public bool Insert(Course model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                try
                {
                    entities.Courses.Add(model);
                    entities.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Update(Course model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                try
                {
                    System.Data.Entity.Infrastructure.DbEntityEntry<Course> entry = entities.Entry<Course>(model);
                    entry.State = System.Data.EntityState.Modified;
                    entities.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Delete(Course model)
        {
            using (UcAspNetEntities entities = new UcAspNetEntities())
            {
                System.Data.Entity.Infrastructure.DbEntityEntry<Course> entry = entities.Entry<Course>(model);
                entry.State = System.Data.EntityState.Deleted;
                entities.SaveChanges();
                return true;
            }
        }
    }
}